#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void sigcb(int signo){
		printf("recv a signal : SIGPIPE\n");
}

int main(int argc, char *argv[])
{
	if(argc != 3) {
		printf("Usage : ./a.out ip port");
		return -1;
	}
	signal(SIGPIPE, sigcb);
	int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sockfd < 0) {
		perror("socket create failed");
		return -1;
	}

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(argv[2]));
	addr.sin_addr.s_addr = inet_addr(argv[1]);
	socklen_t len = sizeof(struct sockaddr_in);

	int ret = bind(sockfd, (struct sockaddr*)&addr, len);
	if(ret < 0) {
		perror("bind failed");
		return -1;
	}

	ret = listen(sockfd, 5);
	if(ret < 0) {
		return -1;
	}

	while(1) {
		int cli_fd = accept(sockfd, (struct sockaddr*)&cli_addr, &len);
		if(cli_fd == 0) {
			perror("accept");
			continue;
		} 
		while(1){
			struct sockaddr_in cli_addr;
			char buff[1024] = {0};
			ret = recv(cli_fd, buff, 1023, 0);
			if(ret == 0) {
				printf("client shutdown!!\n");
				break;
			} else if(ret < 0) {
				if(errno == EINTR || errno == EAGAIN) {
					continue;
				}
				break;
			}
			printf("client say : %s\n", buff);
			char tmp[1024] = {0};
			scanf("%s",tmp);
			send(cli_fd, tmp, strlen(tmp), 0);
		}
		close(cli_fd);
	}
	close(sockfd);
	return 0;
}
